<?php
namespace app\index\model;

use think\Model;

class Recharge extends Model
{   
    /**
     * 用户充值
     * @param int $user_id 必填,用户的id
     * @param int $amount 必填，充值金额
     * @return stauts
     */
    public function  userRecharge($user_id,$amount){
    	$User   = db('user');
 
        //用户账户充值
        $money = $User->where('id',$user_id)->value('money');
        $new_money = $money+$amount;
        
        $result = $User->where('id',$user_id)->update(array('money'=>$new_money));

        return ($result === 0 || $result ) ? $new_money : false ;
    }
    
     /**
     * 插入用户充值记录
     * @param int $user_id 必填,用户的id
     * @param int $amount 必填，充值金额
     * @param int $type 必填，充值类型 1 微信支付 2.使用红包
     * @return stauts
     */
    public function addRechargeLog($user_id,$amount,$type){
       $insert_info['user_id'] = $user_id;
       $insert_info['amount']  = $amount;
       $insert_info['type']    = $type;
       $insert_info['time']    = time();
       $insert_info['pay_number'] = date('YmdHis',time()).getRandCode(6);
       return db('recharge_log')->insert($insert_info); 
    } 

    //统一下单接口，获取package
    public function pay_place_order($user_id,$amount){
        $prepay = array(
            'appid'            => 'wxa641018b058e4ac9', //小程序qppid
            'body'             => '高端手工台球杆', //支付商品描述
            'mch_id'          => '1326035601', 
            'nonce_str'        => getRandCode(16),//生成随机的32位字符串
            'notify_url'        => 'https://wxa.chaojisales.com/index/pay/index',  //通讯地址
            'openid'           =>  db('user')->where('id',$user_id)->value('openid'),
            'out_trade_no'     => date('YmdHis',time()).getRandCode(6),//商户的订单号
            'spbill_create_ip' => getIP(),//客户端的IP
            'total_fee'        => $amount,//总金额
            'trade_type'       => 'JSAPI'
        );
      
        $xml = '<xml>
                   <appid>'.$prepay['appid'].'</appid>
                   <body>'.$prepay['body'].'</body>
                   <mch_id>'.$prepay['mch_id'].'</mch_id>
                   <nonce_str>'.$prepay['nonce_str'].'</nonce_str>
                   <notify_url>'.$prepay['notify_url'].'</notify_url>
                   <openid>'.$prepay['openid'].'</openid>
                   <out_trade_no>'.$prepay['out_trade_no'].'</out_trade_no>
                   <spbill_create_ip>'.$prepay['spbill_create_ip'].'</spbill_create_ip>
                   <total_fee>'.$prepay['total_fee'].'</total_fee>
                   <trade_type>'.$prepay['trade_type'].'</trade_type>
                   <sign>'.$this->MakeSign($prepay).'</sign>
                </xml>';
       //调用api，自定义对参数进行处理，改请求方式是自定义方式 
        $xml_result = httpRequest('https://api.mch.weixin.qq.com/pay/unifiedorder','POST',$xml);
        $result     = json_decode(json_encode(simplexml_load_string($xml_result, 'SimpleXMLElement', LIBXML_NOCDATA)),true);
      
        $data['nonce_str'] = $prepay['nonce_str'];
        $data['prepay_id'] = $result['prepay_id'];
        $data['nonce_str'] = $prepay['nonce_str'];
        $data['timeStamp'] = time();
       // $data['prepay_id'] = $prepay_id_arr[0];
       
        return $this->getPaySign($data);
    }

    public function getPaySign($data){
        $result['pay_sign']   = strtoupper(md5("appId=wxa641018b058e4ac9&nonceStr=".$data['nonce_str']."&package=prepay_id=".$data['prepay_id']."&signType=MD5&timeStamp=".$data['timeStamp']."&key=d57f65ebb69106cd68d1aacd7b8616d7"));
        $result['time_stamp'] = (string)time();
        $result['nonce_str']  = $data['nonce_str'];
        $result['prepay_id']  = $data['prepay_id'];
        return $result;
    }

    public function MakeSign($prepay)
    {
        //签名步骤一：按字典序排序参数
        ksort($prepay);
        $string = $this->ToUrlParams($prepay);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=d57f65ebb69106cd68d1aacd7b8616d7";
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 格式化参数格式化成url参数
     */
    public function ToUrlParams($prepay)
    {
        $buff = "";
        foreach ($prepay as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

}